package com.smartlbs.service.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.util.StringUtil;
import com.smartlbs.baseframe.utils.ConfigFileUtils;
import com.smartlbs.baseframe.utils.DateUtils;
import com.smartlbs.baseframe.utils.HttpClientUtil;
import com.smartlbs.baseframe.utils.ParseExcelUtil;
import com.smartlbs.baseframe.web.ResponseInfo;
import com.smartlbs.dto.GameInfoDto;
import com.smartlbs.entity.BetInfo;
import com.smartlbs.entity.GameExcleInfo;
import com.smartlbs.entity.OhterChamp.Value;
import com.smartlbs.entity.Bigchamp;
import com.smartlbs.entity.GameInfo;
import com.smartlbs.entity.OtherBet;
import com.smartlbs.entity.OtherBet.GE;
import com.smartlbs.entity.OtherBet.betPlayer;
import com.smartlbs.entity.OtherMatch.Match;
import com.smartlbs.entity.OtherMatch.player;
import com.smartlbs.entity.OtherMatch.playerInfo;
import com.smartlbs.mapper.BetInfoMapper;
import com.smartlbs.mapper.GameIfonMapper;
import com.smartlbs.service.IBetInfoService;
import com.smartlbs.service.IGameInfoService;
import com.smartlbs.service.ISettingService;
import com.smartlbs.vo.BetInfoVo;
import com.smartlbs.vo.GameInfoVo;
import com.sun.mail.handlers.message_rfc822;
import com.sun.swing.internal.plaf.basic.resources.basic;

/**
 * 赛事信息服务层类
 * 
 * @author idaowei
 *
 */
@Service("IGameInfoService")
public class GameInfoServiceImpl implements IGameInfoService {
	
	@Autowired
	private BetInfoMapper betMapper;
	@Autowired
	private GameIfonMapper mapper;
	@Autowired
	private IBetInfoService betInfoService;
	@Autowired
	private ISettingService setService;

	@Override
	public int insert(GameInfo info) {
		// TODO Auto-generated method stub
		return mapper.insert(info);
	}

	@Override
	public int update(GameInfo info) {
		// TODO Auto-generated method stub
		return mapper.update(info);
	}

	@Override
	public int delete(long infoId) {
		// TODO Auto-generated method stub
		return mapper.delete(infoId);
	}

	@Override
	public GameInfo findByid(long infoId) {
		// TODO Auto-generated method stub
		return mapper.findById(infoId);
	}

	@Override
	public List<GameInfo> query(GameInfo info) throws Exception {
		// TODO Auto-generated method stub
		GameInfoDto gameInfoDto = new GameInfoDto();
		BeanUtils.copyProperties(info, gameInfoDto);
		return mapper.find(gameInfoDto);
	}

	@Transactional
	@Override
	public Map<String, Object> insertByfile(MultipartFile file)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<>();
		int result = 0;
		String message = "";
		Map<String, Object> list = ParseExcelUtil.getGameInfo(file);
		if (list != null) {
			result = (int) list.get("result");
			if (result > 0) {

				Map<String, List<GameInfo>> gaMap = (Map<String, List<GameInfo>>) list
						.get("gaMap");
				Map<String, OtherBet> betMap = (Map<String, OtherBet>) list
						.get("betmaps");
				Set<String> keySet = gaMap.keySet();
				for (String key1 : keySet) {
					List<GameInfo> list2 = gaMap.get(key1);
					for (GameInfo gameInfo : list2) {
						gameInfo.setCreateTime(new Date());
						gameInfo.setAllInfo("excel插入数据");
						gameInfo.setSource(2);
						gameInfo.setStatus(1);
						int insert = insert(gameInfo);
						if (insert > 0) {
							OtherBet otherBet = betMap.get(gameInfo
									.getBetName());
							if (otherBet != null) {
								Object json1 = JSONObject.toJSONString(
										otherBet,
										SerializerFeature.WriteMapNullValue);
								String string = json1.toString();
								List<GE> ge = otherBet.getGE();
								betInfoService.insert(gameInfo.getInfoId(), ge);
							}

						}
					}
				}

			} else {
				message = (String) list.get("message");
			}

			map.put("result", result);
			map.put("message", message);
		}

		return map;
	}

	@Override
	public List<GameInfoVo> findbyTime(String time) throws Exception {
		// TODO Auto-generated method stub
		List<GameInfoVo> list = new ArrayList();
		String timeup = DateUtils.getTimes(time);
		List<GameInfo> infos = mapper.findbyTime(time, timeup);
		for (GameInfo gameInfo : infos) {
			GameInfoVo vo = new GameInfoVo();
			BeanUtils.copyProperties(gameInfo, vo);
			vo.setGameTimeStr(DateUtils.dateTostrmm(gameInfo.getGameTime()));
			vo.setCreateTimeStr(DateUtils.dateTostr(gameInfo.getCreateTime()));
			vo.setUpdateTimeStr(DateUtils.dateTostr(gameInfo.getUpdateTime()));

			list.add(vo);
		}
		return list;
	}

	public void insertChamps() throws Exception {

		// TODO Auto-generated method stub
		List<Value> bigchamps = getBigchamps();
		if (bigchamps != null && bigchamps.size() > 0) {
			for (Value bigchamp : bigchamps) {
				Date date = new Date();
				long time = date.getTime();
				Long li = bigchamp.getLI();
				// 查询参数列表
				List<Match> champinfo = getChampinfo(li,bigchamp.getL());
				if (champinfo != null && champinfo.size() > 0) {
					// 赛事的详情信息
						for (Match match : champinfo) {
						GameInfo gameInfo = new GameInfo();
						// 外部id
						GameInfo gameInfoDto = new GameInfo();
						gameInfoDto.setOutId(String.valueOf(match.getLI()));
						// 押注名
						if(!StringUtils.isEmpty(match.getO2())){
							String betName=match.getO1()+"\\/"+match.getO2();
							gameInfoDto.setBetName(betName);
						}else {
							gameInfoDto.setBetName(match.getO1());
						}
						List<GameInfo> querygGameInfo = query(gameInfoDto);
						if (querygGameInfo != null && querygGameInfo.size() > 0) {
							GameInfo gameInfo2 = querygGameInfo.get(0);
							List<BetInfoVo> betInfoVos = betInfoService
									.findbyGameId(gameInfo2.getInfoId());
							if (betInfoVos == null || betInfoVos.size()==0) {
								String name="赛事名: "+gameInfo2.getGameName()+"中,押注名: "+gameInfo2.getBetName()+"中具体押注项";

								betInfoService.insertBet(match.getCI(),
										gameInfo2.getInfoId(),name);
								continue ;
							} else {
								continue ;
							}
						}
						// 外部id
						gameInfo.setOutId(String.valueOf(li));
						// 赛事名称
						gameInfo.setGameName(bigchamp.getL());
						gameInfo.setBetName(gameInfoDto.getBetName());
						// 抓取信息串
						Object json = JSONObject.toJSONString(match,
								SerializerFeature.WriteMapNullValue);
						if (json != null) {
							gameInfo.setAllInfo(String.valueOf(json));
						}
						setGameinfo(gameInfo, match, true, time);

						Object json2 = JSONObject.toJSONString(gameInfo,
								SerializerFeature.WriteMapNullValue);

						gameInfo.setCreateTime(new Date());
						int inset = insert(gameInfo);
						String name="赛事名: "+gameInfo.getGameName()+"中,押注名: "+gameInfo.getBetName()+"中具体押注项";
						betInfoService.insertBet(match.getCI(),
								gameInfo.getInfoId(),name);

					}
				}

			}
		}

	}

	// 提取参赛信息
	public void setGameinfo(GameInfo ifGameInfo, Match info, boolean is1xbet,
			Long time) {

		// 国家
		ifGameInfo.setCountry(String.valueOf(info.getCOI()));
		
		// 选手比赛信息
		List<playerInfo> eInfos = info.getE();

		// 开赛时间
		ifGameInfo.setGameTime(new Date(info.getB() * 1000 + time));
		// 信息来源
		if (is1xbet) {
			ifGameInfo.setSource(1);
		} else {
			ifGameInfo.setSource(2);
		}
		ifGameInfo.setStatus(1);

	}

	public List<Value> getBigchamps() throws Exception {
		// 大赛事列表
		String bigurl = "https://1xbet788.com/LineFeed/GetChampsZip?sport=41&lng=cn&tf=2200000&tz=8&country=90&partner=57&virtualSports=true";
		// 赛事列表 champs==大赛事列表LI
		// 押注项 id==参赛列表CI
		String bigjson = "";
		// String ips = getips();
		bigjson = HttpClientUtil.doGets(bigurl,"查询大赛事");
		ConfigFileUtils.setIpslog(DateUtils.dateTostr(new Date())
				+ "抓取开始 ");
		List<Value> values = null;
		if (!StringUtils.isEmpty(bigjson)) {
			// 赛事词典
			values = JSON.parseArray(
					JSON.parseObject(bigjson).getString("Value"), Value.class);
			changeGameName(values);

		}
		return values;

	}
/** 赛事名词典  替换中英文
 * @param values
 */
	private void changeGameName(List<Value> values){
		Map<String, String> nameMap = ParseExcelUtil.getGameNames();
		for (Value value : values) {
		String l = value.getL();
		String name = nameMap.get(l.toLowerCase());
		if (!StringUtils.isEmpty(name)) {
			value.setL(name);
			}
		}
	}
	// 查询参赛列表
	public List<Match> getChampinfo(Long li,String name) throws Exception {
		String champurl = "https://1xbet788.com/LineFeed/Get1x2_VZip?sports=41&champs="
				+ li
				+ "&count=50&lng=cn&tf=2200000&tz=8&mode=4&country=90&partner=57&getEmpty=true";
		// String ips = getips();
		String text="大赛事: "+name+"中的押注项";
		String champjson = HttpClientUtil.doGets(champurl,text);
		List<Match> parseArray = null;
		if (!StringUtils.isEmpty(champjson)) {
			parseArray = JSON
					.parseArray(JSON.parseObject(champjson).getString("Value"),
							Match.class);
			for (Match match : parseArray) {
				//选手
				List<playerInfo> esInfos = match.getE();
				//小场 名称中英文替换
				String betName = match.getO1().toLowerCase();
				changeBetName(betName, match);
			}
		} 
		return parseArray;
	}
/** 押注名称中英文 
 * @param matchs
 */
	private void changeBetName(String betName,Match match){
	//赛事词典
	Map<String, String> nameMap = ParseExcelUtil.getGameNames();
	if(!StringUtils.isEmpty(betName)){
		Set<String> keySet = nameMap.keySet();
		for (String betStr : keySet) {
			if(StringUtils.isEmpty(betStr)){
				System.out.println(nameMap.get(betStr));
			}
			if(!StringUtils.isEmpty(betName)&&!StringUtils.isEmpty(betStr)){
				String lowerCase = betName.toLowerCase();
				if(lowerCase.contains(betStr.toLowerCase())){
					String[] split = lowerCase.split(betStr);
					String betInfo="";
					if(split.length>0){
						if(split.length==1){
							betInfo=split[0]+nameMap.get(betStr);
						}else {
							betInfo=nameMap.get(betStr)+split[1];
						}
						
						}else {
							betInfo=nameMap.get(betStr);
						}
							match.setO1(betInfo);
					}
				}
			}
		}
	}
/**  选手词典英译文
 * @param playerName
 * @param match
 * @param esInfos
 */
	private void changePalyerName(String playerName,Match match,List<playerInfo> esInfos){
	//选手词典
		Map<String, String> playerNames = ParseExcelUtil.getPlayerNames();

		for (playerInfo playerInfo : esInfos) {
			player pl = playerInfo.getPL();
			if (pl != null) {
				String n = pl.getN();
				String plname = playerNames.get(n);
				if (!StringUtils.isEmpty(plname)) {
				pl.setN(plname);
				}
			}
		}
	}
	@Override
	public List<Bigchamp> findBigchamp() throws Exception {
		// TODO Auto-generated method stub
		List<Bigchamp> findBigchamp = mapper.findBigchamp();
		for (Bigchamp dto : findBigchamp) {
			dto.setGameDate(DateUtils.dateTostrday(dto.getGameTime()));

		}
		return findBigchamp;
	}

	@Override
	public int updateBigchamp(Bigchamp dto) throws Exception {
		// TODO Auto-generated method stub

		return mapper.updateBigchamp(dto);
	}

	@Override
	public int deleteBigchamp(String gameName) throws Exception {
		// TODO Auto-generated method stub

		return mapper.deleteBigchamp(gameName);
	}

	@Override
	public List<GameInfoVo> findByoutId(String gameName) throws Exception {
		// TODO Auto-generated method stub
		List<GameInfo> infos = mapper.findByoutId(gameName);
		List<GameInfoVo> list = new ArrayList();
		for (GameInfo gameInfo : infos) {
			GameInfoVo vo = new GameInfoVo();
			BeanUtils.copyProperties(gameInfo, vo);
			vo.setGameTimeStr(DateUtils.dateTostrmm(gameInfo.getGameTime()));

			list.add(vo);
		}
		return list;
	}

	@Override
	public List<GameInfoVo> findByoutIdands(String outId) throws Exception {
		// TODO Auto-generated method stub
		List<GameInfo> infos = mapper.findByoutIdands(outId);
		List<GameInfoVo> list = new ArrayList();
		for (GameInfo gameInfo : infos) {
			GameInfoVo vo = new GameInfoVo();
			BeanUtils.copyProperties(gameInfo, vo);
			vo.setGameTimeStr(DateUtils.dateTostrmm(gameInfo.getGameTime()));

			list.add(vo);
		}
		return list;
	}

	@Override
	public List<Bigchamp> findBigchampands() throws Exception {
		// TODO Auto-generated method stub
		List<Bigchamp> findBigchamp = mapper.findBigchampands();
		for (Bigchamp dto : findBigchamp) {
			dto.setGameDate(DateUtils.dateTostrday(dto.getGameTime()));

		}
		return findBigchamp;
	}

	@Override
	public List<GameInfoVo> findbyTimeands(String time) throws Exception {
		// TODO Auto-generated method stub
		List<GameInfoVo> list = new ArrayList();
		String timeup = DateUtils.getTimes(time);
		List<GameInfo> infos = mapper.findbyTime(time, timeup);
		for (GameInfo gameInfo : infos) {
			GameInfoVo vo = new GameInfoVo();
			BeanUtils.copyProperties(gameInfo, vo);
			vo.setGameTimeStr(DateUtils.dateTostrmm(gameInfo.getGameTime()));
			vo.setCreateTimeStr(DateUtils.dateTostr(gameInfo.getCreateTime()));
			vo.setUpdateTimeStr(DateUtils.dateTostr(gameInfo.getUpdateTime()));

			list.add(vo);
		}
		return list;
	}

	

	@Override
	public List<GameInfoVo> findByoutIdandBet(String outId) throws Exception {
		// TODO Auto-generated method stub
		List<GameInfo> infos = mapper.findByoutId(outId);
		List<GameInfoVo> list = new ArrayList();
		for (GameInfo gameInfo : infos) {
			GameInfoVo vo = new GameInfoVo();
			BeanUtils.copyProperties(gameInfo, vo);
			vo.setGameTimeStr(DateUtils.dateTostrmm(gameInfo.getGameTime()));
			List<BetInfoVo> betVos = betInfoService.findbyGameId(gameInfo
					.getInfoId());
			if (betVos != null) {
				vo.setBetInfoVo(betVos);
			}
			list.add(vo);
		}
		return list;
	}

	@Override
	public List<Bigchamp> sysFindBigchamp(String gameName,String order,String startDate,String endDate ) throws Exception {
		// TODO Auto-generated method stub
		Map map=new HashMap();
		if(!StringUtil.isEmpty(gameName)){
			map.put("gameName", gameName);
		}
		if(!StringUtil.isEmpty(order)){
			map.put("order", Integer.valueOf(order));
		}
		if(!StringUtil.isEmpty(startDate)&&!StringUtil.isEmpty(endDate)){
			map.put("startDate", startDate+" 00:00");
			map.put("endDate", endDate+" 24:59");
		}
		List<Bigchamp> findBigchamp = mapper.sysFindBigchamp(map);
		for (Bigchamp dto : findBigchamp) {
			dto.setGameDate(DateUtils.dateTostrday(dto.getGameTime()));

		}
		return findBigchamp;
	}

	@Override
	public int changeGameName(String outId) throws Exception{
		List<GameInfo> infos = mapper.findByoutId(outId);
		//赛事词典
		Map<String, String> nameMap = ParseExcelUtil.getGameNames();
		//选手词典
		Map<String, String> playerMap = ParseExcelUtil.getPlayerNames();

		for (GameInfo game : infos) {
			String gameName = game.getGameName();
			String betName = game.getBetName();
			//赛事名称 英译中
			if(!StringUtils.isEmpty(gameName)){
				String name = nameMap.get(gameName.toLowerCase());
				if (!StringUtils.isEmpty(name)) {
					game.setGameName(name);
				}
			}
			//押注名称 英译中
			if(!StringUtils.isEmpty(betName)){
				Set<String> keySet = nameMap.keySet();
				for (String betStr : keySet) {
				
					if(!StringUtils.isEmpty(betStr)&&!StringUtils.isEmpty(betName)){
						String lowerCase = betName.toLowerCase();
						if(lowerCase.contains(betStr.toLowerCase())){
							String[] split = lowerCase.split(betStr.toLowerCase());
							String betInfo="";
							if(split.length>0){
								if(split.length==1){
									betInfo=split[0]+nameMap.get(betStr);
								}else {
									betInfo=nameMap.get(betStr)+split[1];
								}
								
								
							}else{
								betInfo=nameMap.get(betStr);
							}
							
							game.setBetName(betInfo);
						}
					}
					
					
				}
			}
			game.setUpdateTime(new Date());
			int update = update(game);
			
			List<BetInfo> findbyGameId = betMapper.findbyGameId(game.getInfoId());
			//选手信息 英译中
			for (BetInfo bet : findbyGameId) {
				String betInfo = bet.getBetInfo();
				GE g = JSON.parseObject(betInfo, GE.class);
				List<List<betPlayer>> e = g.getE();
				for (List<betPlayer> play : e) {
					for (betPlayer betPlayer : play) {
						player pl = betPlayer.getPL();
						if (pl != null) {
							if (!StringUtils.isEmpty(pl.getN())) {
								String plname = playerMap.get(pl.getN().toLowerCase());
								if (!StringUtils.isEmpty(plname)) {
									pl.setN(plname);
								}
							}
						}
					}
				}
				Object json = JSONObject.toJSONString(g,
						SerializerFeature.WriteMapNullValue);
				bet.setBetInfo(json.toString());
				bet.setUpdateTime(new Date());
				int update2 = betMapper.update(bet);
			}
		}
		
		return 0;
	}

}
